define(["jquery","echarts",'migrate_jqprint','jqprint',"bbcare",
    "as/app/gms/gmsDetail.ui",
    "as/app/gms/gmsDetail.servers"],function(jquery,echarts,migrate,$print,$bb,$ui,$servers){
    var event = {};

    /**
     * 保存指导建议和备注成功后的回调函数
     */
    var saveGuidesCallBack = function(data,info){
        $servers.getGuides(info,getGuidesCallBack);
    }

    /**
     * 保存指导建议和备注
     */
    var onSaveGuides = function(){
        var info = $(this).data("info");
        var id = $(this).attr("id");
        var type = $(this).attr("type");
        var default_text = id == "modifyGuides" ? "暂无指导意见" : "暂无备注";
        var btn_text = id == "modifyGuides" ? "修改建议" : "修改备注";
        var dom = $(this).parent().next();
        if( type == "modify" ){
            dom.attr("contentEditable",true).addClass("edit");
            $(this).attr("type","save").html('<i class="fa fa-check-square" aria-hidden="true"></i>确认修改');
            if( dom.html() == default_text ) dom.html("");
        }else if( type == "save" ){
            dom.removeAttr("contentEditable").removeClass("edit");
            $(this).attr("type","modify").html('<i class="fa fa-pencil-square" aria-hidden="true"></i>' + btn_text);
            var guides = $.trim($("#guides").html());
            var remark = $.trim($("#remark").html());
            if( !guides ){
                $("#guides").html("暂无指导意见");
                guides = "暂无指导意见";
            }
            if( !remark ){
                $("#remark").html("暂无备注");
                remark = "暂无备注";
            }
            var params = {
                "evaluationId": info.answerId,
                "userId": info.userId,
                "guide": guides,
                "remark": remark,
            }
            $servers.saveGuides(params,saveGuidesCallBack,info);
        }
    }

    /**
     * 请求指导意见成功后的回调函数
     */
    var getGuidesCallBack = function(data,info){
        if( data && data.remark ) $("#remark").html(data.remark);
        if( data && data.guide ) $("#guides").html(data.guide);
        // 打印
        $ui.printInfo({
            "id":"printRes",
            "data":info
        });
        var result = JSON.parse(info.answerResult);
        $("#check-res").html(result.ps.stage + "（"+ result.ps.item +"）");
        var guides = (data && data.guide) ? data.guide : (result.ps.guides) ? result.ps.guides : "暂无指导意见";
        $("#check-guide").html(guides);
        var doctorName =JSON.parse($bb.getSessionStorage("account")).alias;
        $("#eva-info").html('<p class="eva-info">评估医生：'+ doctorName +'</p><p class="eva-info">评估日期：'+ result.ps.testTime +'</p>');
        //打印按钮：
        var topbars = [
            {
                "icon":"fa fa-print",
                "name":"打印报告",
                "callback":printReport,
                "params":{"dom":"#printContent"}
            }
        ];
        $bb.toolbar(topbars);
    }

    /**
     * 打印函数
     */
    var printReport = function(){
        var params = $(this).data("params");
        var $pc = $(params.dom);
        $pc.jqprint({
            debug: false, //如果是true则可以显示iframe查看效果（iframe默认高和宽都很小，可以再源码中调大），默认是false
            importCSS: true, //true表示引进原来的页面的css，默认是true。（如果是true，先会找$("link[media=print]")，若没有会去找$("link")中的css文件）
            printContainer: true, //表示如果原来选择的对象必须被纳入打印（注意：设置为false可能会打破你的CSS规则）。
            operaSupport: true//表示如果插件也必须支持歌opera浏览器，在这种情况下，它提供了建立一个临时的打印选项卡。默认是true
        });
        return;
    };

    /**
     * 获取曲线图上需要的数据成功后的回调函数
     */
    var getGmsScoreCallBack = function(data,info){
        var history = $servers.curDeal(data);
        charts({"data":history});
        $servers.getGuides(info,getGuidesCallBack);
    }

    /**
     * 选择评估历史记录
     */
    event.onTestTimeSelect = function(){
        $(this).addClass("active").siblings().removeClass("active");
        var rows = $(this).data("rows");
        var index = $(this).index();
        var data = rows[index];
        $ui.info({
            "id":"gmsDetailInfo",
            "data":data
        });
        // 建议、备注、 图标
        $servers.getGmsScore(data,getGmsScoreCallBack);
        // 修改建议、备注
        $("#modifyGuides,#modifyRemark").unbind("click");
        $("#modifyGuides,#modifyRemark").data({"info":data});
        $("#modifyGuides,#modifyRemark").click(onSaveGuides);
    }

    /**
    * 图表
    */
    var charts = function(obj){
        var arr = $servers.diotArr();
        var myChart = echarts.init(document.getElementById('chart'));
        var option = {
            tooltip: {
                trigger: 'item',
                formatter:function(params, ticket, callback){
                    var val='';
                    if(params.seriesType == "scatter" && params.seriesName == "baby"){
                        var name =JSON.parse(params.data.name);
                        var age = "";
                        var getAge = function(days,pregnancDay,birthday){
                            var age ;
                            if(birthday){
                                age = parseInt((days-pregnancDay)/7) + "周" + (days-pregnancDay)%7 + "天";
                            }else{
                                age = parseInt(pregnancDay/7) + "周" + pregnancDay%7 + "天";
                            }
                            return age;
                        };
                        var getGestationAge = function(days){
                            var age ;
                            age = parseInt(days/7) + "周" + days%7 + "天";
                            return age;
                        };
                        if( name.days*1 >= name.pregnancDay*1 ){
                            age = getAge(name.days*1,name.pregnancDay*1,name.birthday);
                            val += '出生周龄：'+ age;
                        }else{
                            age = getGestationAge(name.days*1);
                            val += '出生胎龄：'+ age;
                        }
                        val += "<br/>"+'记录体位：'+ name.posture + "<br/>"+'运动表现：'+ name.evaRes + "<br/>"+'评估日期：'+ name.testTime;
                    }
                    return val;
                }
            },
            grid: {
                left: '0',
                right: '20',
                bottom: '15',
                top:'10',
                width:'750',
                height:'320',
                containLabel: true
            },
            xAxis: {
                type: 'value',
                min:'182',
                max:"434",
                interval:7,
                name:"周",
                nameLocation:"middle",
                nameGap:"24",
                boundaryGap: false,
                axisLabel: {
                    formatter: function(value,index){
                        if(value % 7 == 0){
                            if(value > 280){
                                return parseInt((value-280) / 7)
                            }else{
                                return parseInt(value / 7);
                            }
                        }
                    }
                },
                splitArea : {
                    show : false
                }
            },
            yAxis:  {
                type: 'value',
                name:"",
                nameLocation:"middle",
                nameGap:"27",
                boundaryGap: false,
                min:0,
                max:7,
                interval:1,
                axisLabel: {
                    textStyle: {
                        color: function (value, index) {
                            var color = ["","#AACA57","#70C6C9","#FACE64","#ED9772","#EF7255","#8B549B","#3B6FB3"];
                            return color[value]
                        }
                    },
                    formatter: function(value,index){
                        var label = ["","N","F","PR","Ch","CS","AF","F-"];
                        return label[index]
                    },
                    fontWeight:"bolder",
                    fontSize:"16"
                },
                splitArea : {
                    show : false
                }
            },
            series: [
                {
                    name: 'bg',
                    type: 'scatter',
                    symbol: 'rect',
                    symbolSize: function(value,number){
                        return [19.5,42]
                    },
                    data:arr,
                    itemStyle: {
                        normal: {
                            color: '#EBEBEB'
                        },
                        emphasis:{
                            color: '#EBEBEB'
                        }
                    },
                    animation:false
                },
                {
                    name:'baby',
                    type:'scatter',
                    symbolSize:"12",
                    data:obj.data
                }
            ]
        };
        myChart.setOption(option);
        $("#printImage").html('<img src="' + myChart.getDataURL({type: "png",backgroundColor: '#fff'}) + '" style="width: 100%;height:100%; "/>');
    };

    return event;
});